﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQClient.DelayedMsg
{

    public class DelayedMessage
    {

        public string SendDelayedMessage()
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost",//IP地址
                Port = 5672,//端口号
                UserName = "admin",//用户账号
                Password = "123456",//用户密码
                VirtualHost = "customer"
            };
            using var connection = factory.CreateConnection();
            using var channel = connection.CreateModel();

            var exchangeName = "delay-exchange";
            var routingkey = "delay.delay";
            var queueName = "delay_queueName";

            //设置Exchange队列类型
            var argMaps = new Dictionary<string, object>() { { "x-delayed-type", "topic" } };
            //设置当前消息为延时队列
            channel.ExchangeDeclare(exchange: exchangeName, type: "x-delayed-message", true, false, argMaps);
            channel.QueueDeclare(queueName, true, false, false, argMaps);
            channel.QueueBind(queueName, exchangeName, routingkey);

            var time = 1000 * 5;
            var message = $"发送时间为 {DateTime.Now:yyyy-MM-dd HH:mm:ss} 延时时间为:{time}";
            var body = Encoding.UTF8.GetBytes(message);
            var props = channel.CreateBasicProperties();
            //设置消息的过期时间
            props.Headers = new Dictionary<string, object>() { { "x-delay", time } };
            channel.BasicPublish(exchange: exchangeName, routingKey: routingkey, basicProperties: props, body: body);
            Console.WriteLine("成功发送消息:" + message);

            return "success";
        }
    }
}
